import doT from '../../../../../../public/vendor/template/doT.js'
import StockSituationApi from '../../../../../../public/js/common/api/pig/stocksituation.api.js';
import watermark from '../../../../../../public/js/common/watermark.js';
import EmployeeMgtApi from '../../../../../../public/js/common/api/hr/hr.api.js';
import WxcodeApi from '../../../../../../public/js/common/api/account/wxcode.api.js';
/**
 * @summary养殖批次存栏情况
 */
(function (window, document, $) {
    let _list = [];
    let _sort = {};
    let _maxAge = 160;
    let _scope = [];
    $(function () {
        $('body').attr('data-weui-theme', 'light');
        init();
        _searchRangeSort();
        initCommand();
        watermarkBgImg();
    });
    const watermarkBgImg = async () => {
        let _userInfo = JSON.parse(Utils.GetSessionStorage("SNLoginUserInfo")) || {};

        // if (!Utils.IsNotNull(_userInfo)) {
        //     let _json = await WxcodeApi.queryUserName();
        //     Utils.SetSessionStorage("SNLoginUserInfo", _json);
        //     return EmployeeMgtApi.getLoginUserToStaff(Utils.GetQueryString('state') || '').then(res => {
        //         watermark.set((_json.un || "") + res.code);// 水印
        //     }).catch(_ => {
        //         watermark.set(_json.un || "");// 水印
        //     });
        // }
        EmployeeMgtApi.getLoginUserToStaff(Utils.GetQueryString('state') || '').then(res => {
            watermark.set((res.name || "") + res.numCode);// 水印
        }).catch(_ => {
            watermark.set(_userInfo.un || "");// 水印
        });
    }
    const init = () => {
        let _json = Utils.ParsingUrl(window.location);
        let _endDate = moment(moment.unix(_json.endDate), 'YYYY-MM-DD hh:mm:ss').format('YYYY-MM-DD');
        $('#time').text(moment(moment.unix(_json.time), 'YYYY-MM-DD hh:mm:ss').format('YYYY-MM-DD HH:mm:ss'))
        StockSituationApi.getFatBatagemi(_endDate).then(res => {
            if (!Utils.IsNotNull(res)) return;
            _searchRange(res.orgNames);
            _maxAge = res.maxAge;
            let _template = doT.template($('#search-range-list-item-template').text());
            _list = res.fatList;
            let _num = 0;
            res.fatList.map(item => {
                _num += item.amount
            });
            $('#commercial').text(_num);
            $('#search-form-index').attr('placeholder', `检索共${_list.length}条数据`);
            $('#batch-number').text(_list.length);
            $('#search-range-list').append(_template({ list: res.fatList, maxAge: res.maxAge }));
            $('#main-body').show();
            $('#main-body-loadmore').hide();
        }).catch(res => {
            if (Utils.IsNotNull(res.responseText)) {
                let _json = JSON.parse(res.responseText);
                if (_json.isSucceed) {
                    $('#commercial').text(0);
                    $('#search-form-index').attr('placeholder', `检索共${0}条数据`);
                    $('#batch-number').text(0);
                    return $('#main-body-loadmore').html(`<span class="weui-loadmore__tips">暂无数据</span>`);
                }
            }
            let _text = '';
            if (res.hasOwnProperty('responseJSON')) {
                _text = res.responseJSON.msg;
            } else {
                _text = '服务异常请联系管理员';
            }
            $('#main-body-loadmore').html(`<span class="weui-loadmore__tips">${_text}</span>`);
        })
    }
    const initCommand = () => {
        weui.searchBar('#search_bar');
        //TODO : 检索范围
        $('#search-range').on('click', function () {
            $('#livestock-pig-stocksituation').css({ 'height': '100%', 'overflow': 'hidden' });
            $("#popup-bottom").popup();
        });
        //TODO : 数据排序
        $('#search-range-sort').on('click', function () {
            $('#livestock-pig-stocksituation').css({ 'height': '100%', 'overflow': 'hidden' });
            $("#popup-bottom-sort").popup();
        });
        //TODO : 禁用点击模态框关闭popup
        $('#popup__overlay,#popup__overlay-sort').on('click', function (e) {
            e.stopPropagation();
        });
        //TODO : 检索范围确定
        $(document).on('click', '#confirm-button', function () {
            $.closePopup();
            _scope = [];
            $('#livestock-pig-stocksituation').removeAttr('style');
            $('#search-range-tags').empty();
            if ($('#popup-bottom-ul input[type=checkbox]:checked').length > 0) {
                $('#popup-bottom-ul input[type=checkbox]:checked').each(function () {
                    let _title = $(this).attr('data-title');
                    let _template = doT.template($('#search-range-popup-tag-template').text());
                    _scope.push($(`#${_title}`).text());
                    $('#search-range-tags').append(_template({ value: $(`#${_title}`).text() }));
                });
            }
            _screening();

        });
        //TODO : 检索范围重置
        $(document).on('click', '#clear-button', function () {
            $('#popup-bottom-ul input[type=checkbox]:checked').prop('checked', false);
        });
        //TODO : 搜索
        $('#search-form').submit(function () {
            _screening();
            return false
        });
        $('#search-form-clear,#search-form-close').on('click', function () {
            console.log('??');
            $('#search-form-index').val('')
            _screening();
        });
        //TODO : 检索范围选中
        $(document).on('click', '#popup-bottom-ul li[data-flag=search-range-popup-li]', function (e) {
            let _index = $(this).attr('data-index');
            let $index = $(`#search-range-popup-input-${_index}`);
            $index.prop('checked', !$index.is(':checked'));
            if ($('#popup-bottom-ul input[type=checkbox]:checked').length > 2) {
                $index.prop('checked', false);
                $.toptip(`最多只能选择两个`, 'warning');
            }

        });
        //TODO : 数据排序选中
        $('#popup-bottom-ul-sort li[data-flag=search-range-popup-li]').on('click', function (e) {
            $.closePopup();
            $('#livestock-pig-stocksituation').removeAttr('style');
            $('#search-range-tags-sort').empty();
            let _p = $(this).children().find('p');
            let _template = doT.template($('#search-range-popup-tag-template').text());
            $('#search-range-tags-sort').append(_template({ value: $(_p).text() }));
            //sort((a, b) => a[sorting] - b[sorting])
            let _sort_ = $(_p).attr('data-sort');
            let _name = $(_p).attr('data-name');
            _sort = {
                sort: _sort_,
                name: _name
            };
            _screening();

        });
    }

    /**
     * 筛选
     */
    const _screening = () => {
        let _listCopy = [..._list];
        let _search = $('#search-form-index').val();
        if (Utils.IsNotNull(_search)) {
            _listCopy = _listCopy.filter(item => item.batchName.indexOf(_search) > -1);
        }
        if (Utils.IsNotNull(_scope)) {
            _listCopy = _listCopy.filter(item => _scope.findIndex(c => (c == item.companyName) || (c == item.farmName)) > -1)
        }
        if (Utils.IsNotNull(_sort)) {
            _listCopy = _listCopy.sort((a, b) => _sort.sort == 'asc' ? a[_sort.name] - b[_sort.name] : b[_sort.name] - a[_sort.name]);
        }
        $('#search-form-index').attr('placeholder', `检索共${_listCopy.length}条数据`);
        $('#batch-number').text(_listCopy.length);
        let _num = 0;
        _listCopy.map(item => {
            _num += item.amount
        });
        $('#commercial').text(_num);
        let _template_ = doT.template($('#search-range-list-item-template').text());
        $('#search-range-list').empty().append(_template_({ list: _listCopy, maxAge: _maxAge }));
    }

    /**
     * 排序
     */
    const _searchRangeSort = () => {
        let _template = doT.template($('#search-range-popup-sort-item-template').text());
        let _list = [
            {
                title: "存栏数：正序",
                sort: "asc",
                name: "amount"
            }, {
                title: "存栏数：倒序",
                sort: "desc",
                name: "amount"
            }, {
                title: "日龄：正序",
                sort: "asc",
                name: "avgAge"
            }, {
                title: "日龄：倒序",
                sort: "desc",
                name: "avgAge"
            }, {
                title: "死淘率：正序",
                sort: "asc",
                name: "deathrate"
            }, {
                title: "死淘率：倒序",
                sort: "desc",
                name: "deathrate"
            },

        ];
        $('#popup-bottom-ul-sort').append(_template({ list: _list }));
        $('#popup-bottom-ul-sort').css({ 'max-height': '75vh', 'overflow-y': 'scroll' });
    }

    /**
     * 检索范围
     */
    const _searchRange = (list) => {
        let _template = doT.template($('#search-range-popup-item-template').text());
        $('#popup-bottom-ul').append(_template({ list: list }));
        $('#popup-bottom-ul').css({ 'max-height': '75vh', 'overflow-y': 'scroll' });
    }

})(window, document, jQuery)